<template>
  <div class="policy-container">
    <!-- 头部区域 -->
    <div class="header-container">
      <div class="emergency-header">
        <div class="black-block"></div>
        <div class="red-title">
          <el-icon><Document /></el-icon>
          政策信息
        </div>
      </div>
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索政策..."
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 政策列表 -->
    <div class="policy-list">
      <div v-if="loading" class="loading-container">
        <el-icon class="loading-icon"><Loading /></el-icon>
        加载中...
      </div>

      <template v-else>
        <div
          v-for="policy in filteredPolicies"
          :key="policy.id"
          class="policy-card"
          @click="showPolicyDetail(policy)"
        >
          <div class="policy-main">
            <div class="policy-title">
              {{ policy.title }}
              <el-tag
                v-for="tag in policy.tags"
                :key="tag"
                class="policy-tag"
                :type="tagTypeMap[tag] || 'info'"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="policy-meta">
              <span class="publish-date">{{ policy.publishDate }}</span>
              <span class="department">{{ policy.department }}</span>
            </div>
          </div>
          <div class="policy-actions">
            <el-icon
              class="star-icon"
              :class="{ 'starred': policy.starred }"
              @click.stop="toggleStar(policy)"
            >
              <StarFilled v-if="policy.starred" />
              <Star v-else />
            </el-icon>
          </div>
        </div>

        <div v-if="!filteredPolicies.length" class="empty-state">
          <el-icon class="empty-icon"><DocumentDelete /></el-icon>
          <p>暂无相关政策信息</p>
        </div>
      </template>
    </div>

    <!-- 政策详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      class="policy-dialog"
      center="center"
    >
      <div class="dialog-header">
        <div class="dialog-title">{{ currentPolicy.title }}</div>
        <div class="tags-container">
          <el-tag
            v-for="tag in currentPolicy.tags"
            :key="tag"
            :type="tagTypeMap[tag] || 'info'"
            class="tag-margin"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div class="publish-info">
          发布日期：{{ currentPolicy.publishDate }} |
          生效日期：{{ currentPolicy.effectiveDate }}
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="14">
          <div class="detail-section">
            <h3><el-icon><Document /></el-icon> 政策内容</h3>
            <pre class="policy-content">{{ currentPolicy.content }}</pre>
          </div>
        </el-col>

        <el-col :span="10">
          <div class="detail-section">
            <h3><el-icon><InfoFilled /></el-icon> 基本信息</h3>
            <div class="info-box">
              <div class="info-item">
                <span class="label">发布部门：</span>
                <el-tag type="warning">{{ currentPolicy.department }}</el-tag>
              </div>
              <div class="info-item">
                <span class="label">联系方式：</span>
                <span class="copyable" @click="copyContact(currentPolicy.contact)">
                  {{ currentPolicy.contact }}
                </span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3><el-icon><Paperclip /></el-icon> 相关文件</h3>
            <div
              v-for="file in currentPolicy.attachments"
              :key="file.name"
              class="file-item"
            >
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ file.name }}</span>
              <el-button
                type="primary"
                size="small"
                @click="downloadFile(file)"
              >
                下载 ({{ file.size }})
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>

      <div class="detail-section">
        <h3><el-icon><Connection /></el-icon> 相关法律</h3>
        <el-row>
          <el-col :span="14">
            <div class="related-laws">
              <el-tag
                v-for="law in currentPolicy.relatedLaws"
                :key="law"
                class="law-tag"
              >
                {{ law }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="10">
            <div class="button-container">
              <el-button
                type="primary"
                plain
                @click="openLink(currentPolicy.link)"
              >
                查看官方原文
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  Document,
  Search,
  Star,
  StarFilled,
  Loading,
  DocumentDelete,
  InfoFilled,
  Paperclip,
  Connection
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Policy {
  id: number
  title: string
  content: string
  publishDate: string
  effectiveDate: string
  department: string
  tags: string[]
  starred: boolean
  attachments: {
    name: string
    size: string
    url: string
  }[]
  relatedLaws: string[]
  link: string
  contact: string
}

// 响应式数据
const searchQuery = ref('')
const loading = ref(true)
const detailVisible = ref(false)
const currentPolicy = ref<Policy>({} as Policy)
const policies = ref<Policy[]>([])

// 修复类型错误
const tagTypeMap: Record<string, 'danger' | 'success' | 'warning' | 'info'> = {
  '紧急': 'danger',
  '民生': 'success',
  '法律': 'warning',
  '财政': 'info',
  '教育': 'info',
  '医疗': 'info'
} as const

// 模拟异步加载
const fetchPolicies = () => {
  setTimeout(() => {
    policies.value = [
      {
        id: 1,
        title: '失踪人口救助法',
        content: `第一章 总则\n第一条 为了保护失踪人口及其家属的合法权益，制定本法...`,
        publishDate: '2023-01-15',
        effectiveDate: '2023-03-01',
        department: '民政部',
        tags: ['法律', '社会'],
        starred: false,
        attachments: [
          {
            name: '失踪人口救助法全文.pdf',
            size: '1.2MB',
            url: '/laws/missing-persons-assistance.pdf'
          }
        ],
        relatedLaws: ['刑法第234条', '民法典第104条'],
        link: 'http://law.gov/missing-persons-assistance',
        contact: '失踪人口热线：12345'
      },
      {
        id: 2,
        title: '失踪人口信息登记管理办法',
        content: '明确失踪人口信息的登记、管理和发布机制...',
        publishDate: '2023-04-20',
        effectiveDate: '2023-06-01',
        department: '公安部',
        tags: ['法律', '社会'],
        starred: true,
        attachments: [
          {
            name: '失踪人口信息登记管理办法.docx',
            size: '1.5MB',
            url: '/laws/missing-persons-registration.docx'
          }
        ],
        relatedLaws: ['治安管理处罚法', '反家庭暴力法'],
        link: 'http://police.gov/missing-persons-registration',
        contact: '举报电话：110'
      },
      {
        id: 3,
        title: '失踪儿童保护法',
        content: '针对失踪儿童的保护措施和救助机制...',
        publishDate: '2023-07-01',
        effectiveDate: '2023-09-01',
        department: '儿童保护委员会',
        tags: ['法律', '儿童'],
        starred: false,
        attachments: [
          {
            name: '失踪儿童保护法.pdf',
            size: '1.0MB',
            url: '/laws/missing-children-protection.pdf'
          }
        ],
        relatedLaws: ['未成年人保护法', '刑法第237条'],
        link: 'http://children.gov/missing-children-protection',
        contact: '儿童保护热线：12348'
      },
      {
        id: 4,
        title: '失踪人口救助基金管理办法',
        content: '为失踪人口及其家属提供经济支持的管理办法...',
        publishDate: '2023-08-15',
        effectiveDate: '2023-10-01',
        department: '民政部',
        tags: ['法律', '社会'],
        starred: false,
        attachments: [
          {
            name: '失踪人口救助基金管理办法.pdf',
            size: '1.3MB',
            url: '/laws/missing-persons-fund-management.pdf'
          }
        ],
        relatedLaws: ['社会救助法', '民法典'],
        link: 'http://law.gov/missing-persons-fund-management',
        contact: '热线电话：12345'
      },
      {
        id: 5,
        title: '失踪人口案件侦查程序',
        content: '规范失踪人口案件的侦查程序和责任...',
        publishDate: '2023-09-10',
        effectiveDate: '2023-11-01',
        department: '公安部',
        tags: ['法律', '侦查'],
        starred: true,
        attachments: [
          {
            name: '失踪人口案件侦查程序.docx',
            size: '1.4MB',
            url: '/laws/missing-persons-investigation-procedure.docx'
          }
        ],
        relatedLaws: ['刑事诉讼法', '治安管理处罚法'],
        link: 'http://police.gov/missing-persons-investigation-procedure',
        contact: '举报电话：110'
      }
    ]
    loading.value = false
  }, 1000)
}

// 计算属性
const filteredPolicies = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return policies.value.filter(p =>
    p.title.toLowerCase().includes(query) ||
    p.content.toLowerCase().includes(query) ||
    p.tags.some(tag => tag.toLowerCase().includes(query))
  )
})

// 方法
const toggleStar = (policy: Policy) => {
  policy.starred = !policy.starred
  ElMessage.success(policy.starred ? '已收藏' : '已取消收藏')
}

const showPolicyDetail = (policy: Policy) => {
  currentPolicy.value = policy
  detailVisible.value = true
}

const handleSearch = () => {
  console.log('执行搜索:', searchQuery.value)
}

const downloadFile = (file: Policy['attachments'][number]) => {
  window.open(file.url, '_blank')
  ElMessage.success('开始下载文件')
}

const openLink = (url: string) => {
  window.open(url, '_blank')
}

const copyContact = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('联系方式已复制')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

// 生命周期钩子
onMounted(fetchPolicies)
</script>

<style scoped>
.policy-container {
  padding: 20px;
  border-radius: 8px;
  height: 100%;
  width: 100%;
  scrollbar-width: thin;
  scrollbar-color: rgba(155, 42, 42, 0.8) transparent;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.emergency-header {
  display: flex;
  height: 50px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.black-block {
  width: 10px;
  background: var(--reverse-background-color);
}

.red-title {
  flex: 1;
  background: #f45c5c;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-size: 22px;
  font-weight: 600;
  gap: 10px;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.policy-list {
  overflow: auto;
  position: relative;
  height: calc(100% - 50px);
}

.policy-card {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.policy-main {
  flex: 1;
  padding-right: 20px;
}

.policy-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.policy-tag {
  height: 24px;
}

.policy-meta {
  font-size: 12px;
  display: flex;
  gap: 15px;
}

.policy-actions {
  display: flex;
  align-items: center;

  .star-icon {
    font-size: 20px;
    transition: all 0.3s;

    &:hover {
      color: #f7ba2a;
      transform: scale(1.2);
    }

    &.starred {
      color: #f7ba2a;
    }
  }
}

/* 详情弹窗样式 */
.policy-dialog {
  .dialog-header {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .dialog-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .tags-container {
      display: flex;
      justify-content: center;
      margin-bottom: 8px;
    }

    .publish-info {
      font-size: 14px;
    }
  }

  .tag-margin {
    margin-right: 8px;
  }

  .detail-section {
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      margin: 0 0 12px 0;
      display: flex;
      align-items: center;

    }
  }

  .policy-content {
    padding: 15px;
    border-radius: 4px;
    line-height: 1.6;
    white-space: pre-wrap;
    font-family: 'Microsoft YaHei', sans-serif;
    max-height: 400px;
    overflow-y: auto;
  }

  .info-box {
    border-left: 3px solid #9b2a2a;
    padding-left: 15px;

    .info-item {
      margin-bottom: 12px;

      .label {
        margin-right: 8px;
      }

      .copyable {
        cursor: pointer;
        &:hover {
          text-decoration: underline;
          color: #9b2a2a;
        }
      }
    }
  }

  .file-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid #eee;

    .file-name {
      flex: 1;
      margin: 0 12px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .related-laws {
    margin-bottom: 15px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

/* 加载和空状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;

  .loading-icon {
    font-size: 32px;
    margin-bottom: 10px;
    animation: rotating 2s linear infinite;
  }
}

.empty-state {
  text-align: center;
  padding: 40px 0;

  .empty-icon {
    font-size: 50px;
    margin-bottom: 10px;
  }
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: -10px;
}
</style>
